/**
 *  入口文件
 *  使用koa作为http服务器
 */

const koa = require('koa');
const static = require('koa-static')
const bodyParser = require('koa-bodyparser');
const conditional = require('koa-conditional-get');
const etag = require('koa-etag');
const router = require('./routes');
const config = require('./config').config;

global.ErrorLog = require('./libs/ErrorLog');

require('./utils/BasicFuntion');

const app = new koa();

// etag works together with conditional-get
app.use(conditional());
app.use(etag());

// 全局异常处理
app.use(async(ctx, next) => {
    try {
        await next();
        if (ctx.status === 404) ctx.throw(404);
    } catch (err) {
        if (ctx.status === 404) {
            console.error(ctx.path);
            global.ErrorLog.write(ctx.path);
        }
        console.error(err);
        global.ErrorLog.write(err.stack);
        ctx.status = err.status || 500;
        // return ctx.body = err.stack; //打印调用栈
        return ctx.body = err.message; //打印错误信息
    }
});
app.use(static('./static'));
app.use(bodyParser());
app.use(router.routes());
app.listen(config.port, () => {
    console.log("You can debug your app with http://" + config.host + ':' + config.port);
});
